use crate::db::insert_user_message;
use log::{error, info, warn};
use teloxide::prelude::Requester;
use teloxide::prelude::*;
use teloxide::types::User;

use crate::structs::message::MessageConstructor;
use crate::NUMBERS;

const DEFAULT_JSON: &str = r#"{
            "id":1087968824,
             "is_bot":false,
             "first_name":"Unknown"
         }"#;

pub async fn handle_send_message(
    bot: Bot,
    message: Message,
    pager_number: u16,
    text: String,
) -> ResponseResult<()> {
    let f = NUMBERS.read().unwrap().get_info_pair(pager_number);
    let (cap_code, frequency) = match f {
        Ok(v) => v,
        Err(e) => {
            bot.send_message(message.chat.id, e).await?;
            return Ok(());
        }
    };

    let actual = serde_json::from_str::<User>(DEFAULT_JSON).unwrap();

    let from_user: String = format!(
        "@{}",
        message
            .from()
            .unwrap_or(&actual)
            .username
            .as_ref()
            .unwrap_or(&"unknown".to_string())
    );
    let m = MessageConstructor::default()
        .from(from_user)
        .to_cap(cap_code)
        .text(text)
        .freq(frequency)
        .build();
    match m {
        Err(e) => {
            let _ = bot.send_message(message.chat.id, "Error while message construction");
            warn!("{}", e.to_string())
        }
        Ok(v) => {
            match insert_user_message(v) {
                Ok(_) => {
                    info!("Save user message is OK");
                    bot.send_message(message.chat.id, "Sent!").await?;
                }
                Err(e) => {
                    error!("{}", e);
                    let _ = bot.send_message(message.chat.id, "Error while message save");
                }
            };
        }
    }
    Ok(())
}
